package com.aote.servlet;

import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.aote.entity.EntityTypeFactory;
import com.browsesoft.Entity;
import com.browsesoft.EntityManager;
import com.browsesoft.util.StreamHelper;

/**
 * 文件下载实体
 * 
 */
public class FileDownloadServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public FileDownloadServlet() {
		super();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			// 根据实体类型得到实体，得到文件路径
			String filePathNameAttr = request.getParameter("filepathattr");
			String tableName = request.getParameter("tablename");
			String id = request.getParameter("id");
			String fileNameAttr = request.getParameter("filenameattr");
			// 如果发送文件
			Entity entity = this.getEntity(tableName, id);
			String filePathName = (String) entity.getAttributes().get(
					filePathNameAttr);
			if (filePathName == null || filePathName.equals("")) {
				doFileNotFoundResponse(response, null, "无文件");
				return;
			}
			// 得到文件名
			String fileName = "";
			if (fileNameAttr != null && !fileNameAttr.equals("")) {
				fileName = (String) entity.getAttributes().get(fileNameAttr);
			} else {
				fileName = filePathName.substring(
						filePathName.lastIndexOf("/") + 1, filePathName
								.length());
			}
			fileName = new String(fileName.getBytes(), "iso8859-1");
			// 设置响应的各种参数
			response.setStatus(HttpServletResponse.SC_OK);
			response
					.setContentType("application/octet-stream;charset=\"gb2312\"");
			response.addHeader("Content-Disposition", "attachment;filename=\""
					+ fileName + "\"");
			// 把文件的内容送入响应流中
			InputStream is = new FileInputStream(filePathName);
			OutputStream os = new BufferedOutputStream(response
					.getOutputStream());
			StreamHelper.transformStream(is, os);
			is.close();
			response.flushBuffer();
			os.close();
			response.getOutputStream().close();
		} catch (Exception e) {
			doFileNotFoundResponse(response, e, null);
		}
	}

	/**
	 * 如果用户请求的资源未找到,应该返回的信息
	 * 
	 * @param response
	 *            响应
	 */
	private void doFileNotFoundResponse(HttpServletResponse response,
			Exception e, String message) {
		// 设置响应状态为未找到请求的资源
		response.setStatus(HttpServletResponse.SC_OK);
		response.setContentType("text/html; charset=gb2312");
		// 给用户信息提示
		try {
			if (message == null) {
				response.getWriter().write("<h1>" + e.getMessage() + "</h1>");
			} else {
				response.getWriter().write("<h1>" + message + "</h1>");
			}
		} catch (IOException ex) {
		}
	}

	private Entity getEntity(String tableName, String id) {
		try {
			String condition = "id='" + id + "'";
			String className = EntityTypeFactory.getInstance()
					.getClassNameByTableName(tableName);
			Class c = Class.forName(className);
			List list = EntityManager.getInstance().getEntities(tableName,
					condition, c);
			Entity entity = (Entity) list.get(0);
			return entity;
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		}
	}
}
